import CryptoJS from 'crypto-js'

// 生成随机密钥（仅在开发环境中使用）
const generateRandomKey = () => {
  return CryptoJS.lib.WordArray.random(32).toString() // 32 字节的随机密钥
}
// 从环境变量获取密钥，如果没有则生成一个随机密钥
const SECRET_KEY = import.meta.env.VITE_STORAGE_SECRET || generateRandomKey()

export const secureStorage = {
  set(key: string, value: string) {
    const encrypted = CryptoJS.AES.encrypt(value, SECRET_KEY).toString()
    localStorage.setItem(key, encrypted)
  },

  get(key: string) {
      const encrypted = localStorage.getItem(key)
    //   return encrypted
    // if (!encrypted) return null

    try {
      const bytes = encrypted ? CryptoJS.AES.decrypt(encrypted, SECRET_KEY) : null
      return bytes?.toString(CryptoJS.enc.Utf8)
    } catch {
      return null
    }
  },

  remove(key: string) {
    localStorage.removeItem(key)
  },
}